//
//  OrderDatailViewController.m
//  HomeDelivery
//
//  Created by apple on 16/7/26.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "OrderDatailViewController.h"
#import "CellOne.h"
#import "CellTwo.h"
#import "OrderDetailData.h"
@interface OrderDatailViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *_headView;
    OrderDetailData *_data;
    UIButton *_bottomBtn;
    UIView *_view;
}
@property(nonatomic,strong)UITableView *mainTableView;

@end

@implementation OrderDatailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"订单详情";
    self.view.backgroundColor=LIGHTGRAY;
    [self.view addSubview:self.mainTableView];
    UIBarButtonItem *left=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_action_white"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem=left;
    UIImageView *imageView=[self findHairlineImageViewUnder:self.navigationController.navigationBar];
    imageView.hidden=YES;
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self setUpBtn];
    [self getData];
    if ([self.mainTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.mainTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.mainTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.mainTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
#pragma mark--表分割线条通栏
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}

#pragma mark--获取数据
-(void)getData
{
    //http://192.168.1.107:35568/Order/OrderDetail/{OrderID}/{AdminAccount}/{VerNumber}/{ClientType}/{Timestamp}/{Sign}
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"OrderID":_orderID,
                        @"AdminAccount":ADMINACCOUNT,
                        @"VerNumber":VERNUM,
                        @"ClientType":CLIENTTYPE,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Order/OrderDetail/%@/%@/%@/%@/%@/%@",_orderID,ADMINACCOUNT,VERNUM,CLIENTTYPE,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andFinishedWith:^(id response, NSError *error)
     {
         [MBProgressHUD hideHUDForView:self.view];
         if (error)
         {
             [MBProgressHUD showError:@"请求失败"];
         }else
         {
             if ([response[@"IsSuccess"]integerValue]==1)
             {
                 if (response[@"ReturnObject"]!=[NSNull null]) {
                     NSDictionary *dic=response[@"ReturnObject"];
                     _data=[[OrderDetailData alloc]init];
                     [_data setValuesForKeysWithDictionary:dic];
                     UIImageView *imageview=[_view viewWithTag:[_data.OrderStatus integerValue]];
                     if (imageview)
                     {
                         imageview.image=[UIImage imageNamed:@"order_state_down"];
                         imageview.bounds=CGRectMake(0, 0, 15, 15);
                         imageview.layer.cornerRadius=15/2.0;
                         imageview.clipsToBounds=YES;
                     }
                     if ([_data.OrderStatus integerValue]==30) {
                         [_bottomBtn setTitle:@"确认取件" forState:UIControlStateNormal];
                     }else if ([_data.OrderStatus integerValue]==60)
                     {
                         [_bottomBtn setTitle:@"确认洗涤" forState:UIControlStateNormal];
                     }
                     else if ([_data.OrderStatus integerValue]==90)
                     {
                         [_bottomBtn setTitle:@"确认送件" forState:UIControlStateNormal];
                     }else
                     {
                        [_bottomBtn setTitle:@"已完成" forState:UIControlStateNormal];
                     }
                     [_mainTableView reloadSectionIndexTitles];
                     [_mainTableView reloadData];
                 }
             }else
             {
                 [MBProgressHUD showError:response[@"ReturnString"]];
             }
         }
     }];
}
#pragma mark--按钮
-(void)setUpBtn
{
   _bottomBtn =[[UIButton alloc]initWithFrame:CGRectMake(10, HEIGHT-60, WIDTH-20, 48)];
    _bottomBtn.backgroundColor=[UIColor colorWithRed:247/255.0 green:118/255.0 blue:64/255.0 alpha:1];
    _bottomBtn.layer.cornerRadius=5;
    _bottomBtn.clipsToBounds=YES;
    [_bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_bottomBtn addTarget:self action:@selector(clickOnBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomBtn];
}
-(void)clickOnBtn:(UIButton *)btn
{
    NSString *title=[btn titleForState:UIControlStateNormal];
    //调接口
    if (!_data)
    {
        return;
    }
    NSString *message=[NSString stringWithFormat:@"是否%@？确认后不可修改",title];
    [ZMAlertView sharedAlertViewWithTitle:@"提示" andMessage:message andSureBtnTitle:@"确认" sureBtnIsDestructive:YES andCancleTitle:@"取消" cancleBtnIsDestructive:NO SureBlock:^{
        if ([_data.OrderStatus integerValue]==30) {
            [self sureOrderWithUrlString:@"Order/FinishColl" andDicString:@"m_FinishCollPara"];
        }else if ([_data.OrderStatus integerValue]==60)
        {
            [self sureOrderWithUrlString:@"Order/FinishWash" andDicString:@"m_FinishWashPara"];
        }else if ([_data.OrderStatus integerValue]==90)
        {
            [self sureOrderWithUrlString:@"Order/FinishDeli" andDicString:@"m_FinishDeliPara"];
        }

    } CancleBlock:nil];
    
}
-(void)sureOrderWithUrlString:(NSString *)urlString andDicString:(NSString *)dicString
{
    //http://192.168.1.107:35568/User/ModPwd
    //m_FinishCollPara(AdminAccount,OrderID,Timestamp,Sign)
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{
                        @"AdminAccount":ADMINACCOUNT,
                        @"OrderID":_data.OrderID,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSDictionary *dataDic=@{
                            @"AdminAccount":ADMINACCOUNT,
                            @"OrderID":_data.OrderID,
                            @"Timestamp":timeStamp,
                            @"Sign":sign};
    NSDictionary *requestDic=@{dicString:dataDic};
    [RequestTool requestDataWithType:@"post" andUrlString:urlString andParameters:requestDic andFinishedWith:^(id response, NSError *error)
     {
         [MBProgressHUD hideHUDForView:self.view];
         if (error)
         {
             [MBProgressHUD showError:@"请求失败"];
         }else
         {
             if ([response[@"IsSuccess"]integerValue]==1)
             {
                 [MBProgressHUD showSuccess:response[@"ReturnObject"]];
                 [self.navigationController popViewControllerAnimated:YES];
                 
             }else
             {
                 [MBProgressHUD showError:response[@"ReturnString"]];
             }
         }
     }];

}
#pragma mark--表
-(UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64-70) style:UITableViewStylePlain];
        _mainTableView.delegate=self;
        _mainTableView.dataSource=self;
        _mainTableView.tableHeaderView=[UIView new];
        [_mainTableView registerNib:[UINib nibWithNibName:@"CellOne" bundle:nil] forCellReuseIdentifier:@"cellOne"];
        [_mainTableView registerNib:[UINib nibWithNibName:@"CellTwo" bundle:nil] forCellReuseIdentifier:@"cellTwo"];
    }
    return _mainTableView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 90;
    }
    return 30;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        if (![_data.m_OrderPro isKindOfClass:[NSNull class]])
        {
            if(![_data.m_Discount isKindOfClass:[NSNull class]]&&_data.m_Discount.count >0)
            {
                return _data.m_OrderPro.count+1+_data.m_Discount.count;
            }else
            {
                return _data.m_OrderPro.count+1;
            }
        }else
        {
            return 0;
        }
        
    }else if (section==1)
    {
        return 4;
    }else if (section==2)
    {
        return 5;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
  if (indexPath.section==1)
    {
        if (indexPath.row==3)
        {
            return 50;
        }
        return 40;
    }
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        if (!_headView)
        {
            _headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 90)];
            _headView.backgroundColor=LIGHTGRAY;
            
            _view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 60)];
            _view.backgroundColor=[UIColor colorWithRed:247/255.0 green:118/255.0 blue:64/255.0 alpha:1];
            [_headView addSubview:_view];
            
            CGFloat width=(WIDTH-80)/5.0;
            for (int i=0; i<4; i++) {
                UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(i*(10+width+10)+width, 15, 10, 10)];
                image.backgroundColor=[UIColor whiteColor];
                image.layer.cornerRadius=5;
                image.tag=(i+1)*30;
                image.clipsToBounds=YES;
                [_view addSubview:image];
                
                if (i<3) {
                    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(image.frame)+5, 20, width, 1)];
                    line.backgroundColor=[UIColor whiteColor];
                    [_view addSubview:line];
                }
                
                UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(image.frame)-8, CGRectGetMaxY(image.frame)+5, 50, 20)];
                label.textColor=[UIColor whiteColor];
                label.font=[UIFont systemFontOfSize:14];
                label.text=@[@"取件",@"清洗",@"送回",@"完成"][i];
                [_view addSubview:label];
            }
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 60, WIDTH-20, 30)];
            label.text=@"订单明细";
            label.backgroundColor=LIGHTGRAY;
            label.textColor=[UIColor darkGrayColor];
            label.font=[UIFont systemFontOfSize:13];
            [_headView addSubview:label];
        }
           return _headView;
    }else
    {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
        view.backgroundColor=LIGHTGRAY;
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, WIDTH-20, 30)];
        label.text=@[@"取送信息",@"订单信息"][section-1];
        label.textColor=[UIColor darkGrayColor];
        label.font=[UIFont systemFontOfSize:13];
        [view addSubview:label];
        return view;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        CellOne *cellOne=[tableView dequeueReusableCellWithIdentifier:@"cellOne" forIndexPath:indexPath];
        cellOne.coupon.hidden=YES;
        cellOne.discount.hidden=YES;
        cellOne.orderCoutLbl.hidden=YES;
        if (_data.m_OrderPro)
        {
             NSArray *arr=_data.m_OrderPro;
            if (indexPath.row>=0 && indexPath.row<arr.count)
            {
                NSArray *Arr=_data.m_OrderPro;
                NSDictionary *dic=Arr[indexPath.row];
                cellOne.nameLbl.text=dic[@"ItemName"];
                cellOne.countLbl.text=[NSString stringWithFormat:@"x%@",dic[@"ItemCount"]];
                cellOne.priceLbl.text=[NSString stringWithFormat:@"￥%@",dic[@"TotalPrice"]];
            }else
            {
                if (_data.m_Discount)
                {
                    NSArray *disCount=_data.m_Discount;
                    if (indexPath.row>=arr.count && indexPath.row<arr.count+disCount.count)
                    {
                        //优惠券
                        cellOne.coupon.hidden=NO;
                        cellOne.discount.hidden=NO;
                        
                        NSDictionary *dic=disCount[indexPath.row-arr.count];
                      cellOne.discount.text=dic[@"DiscountName"];
                        cellOne.priceLbl.text=[NSString stringWithFormat:@"-￥%@",dic[@"DiscountPrice"]];
                        
                    }else if (indexPath.row==arr.count+disCount.count)
                    {
                        cellOne.orderCoutLbl.hidden=NO;

                        cellOne.orderCoutLbl.text=[NSString stringWithFormat:@"订单：￥%@ -优惠%@",_data.ProPrice,_data.DiscountPrice];
                        cellOne.priceLbl.textColor=[UIColor lightGrayColor];
                        NSString *sumPrice=[NSString stringWithFormat:@"实付：¥%@",_data.RealPrice];
                        NSInteger length3=[NSString stringWithFormat:@"%@",_data.RealPrice].length;
                        NSMutableAttributedString *attriString1 = [[NSMutableAttributedString alloc] initWithString:sumPrice];
                        //把价格的字体颜色变为红色
                        [attriString1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, length3+1)];
                        [attriString1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(3, length3+1)];
                        [cellOne.priceLbl setAttributedText:attriString1];
                    }
                }else
                {
                    if (indexPath.row==arr.count) {
                        cellOne.orderCoutLbl.hidden=NO;
                        cellOne.orderCoutLbl.text=[NSString stringWithFormat:@"订单：￥%@ -优惠%@",_data.ProPrice,_data.DiscountPrice];
                        
                        cellOne.priceLbl.textColor=[UIColor lightGrayColor];
                        NSString *sumPrice=[NSString stringWithFormat:@"实付：¥%@",_data.RealPrice];
                        NSInteger length3=[NSString stringWithFormat:@"%@",_data.RealPrice].length;
                        NSMutableAttributedString *attriString1 = [[NSMutableAttributedString alloc] initWithString:sumPrice];
                        //把价格的字体颜色变为红色
                        [attriString1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, length3+1)];
                        [attriString1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(3, length3+1)];
                        [cellOne.priceLbl setAttributedText:attriString1];
                    }

                    }
                }
            }
        return cellOne;
    }else
    {
        CellTwo *cellTwo=[tableView dequeueReusableCellWithIdentifier:@"cellTwo" forIndexPath:indexPath];

        NSArray *textArr1=@[@"取送方式:",@"预约时间:",@"联系电话:",@"取送地址:"];
         NSArray *textArr2=@[@"订单编号:",@"下单时间:",@"订单挂起:",@"挂起原因:",@"订单备注:"];
        if (_data) {
            NSArray *dataArr1=@[_data.CollType,_data.ReserveDate,_data.Mobile,[NSString stringWithFormat:@"%@ %@ %@",_data.ReceiveName,_data.MrOrMs,_data.RAddress]];
           
            NSArray *dataArr2=@[_data.OrderID,_data.CreateTime,_data.OrderStatusText,_data.OrderStatusRemark,_data.Remark];
            cellTwo.dataLbl.text=@[dataArr1,dataArr2][indexPath.section-1][indexPath.row];
        }
          cellTwo.titleLbl.text=@[textArr1,textArr2][indexPath.section-1][indexPath.row];
        
        return cellTwo;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


@end
